import { notification } from '@/services/common';
import axios from 'axios';

enum CODE {
  SUCCESS = 1,
  ERROR = 0,
  TOKEN_ERROR = -99
}

const baseURL = '';

const AUTH_TOKEN = localStorage.getItem('token') || '';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.timeout = 10000;
axios.defaults.headers.get['Content-Type'] = 'application/json;charset=UTF-8';
axios.defaults.headers.post['Content-Type'] = 'multipart/form-data;charset=UTF-8';

const http = axios.create({
  baseURL,
  withCredentials: true // 允许跨域请求携带凭证
});

http.interceptors.response.use(
  (response) => {
    const res = response.data;
    if (response.data.code !== CODE.SUCCESS) {
      notification({
        title: '提示',
        message: res.msg,
        type: 'error',
        duration: 3000
      })
    }
    return response.data;
  },
  (error) => {
    let message = '';
    const code = error.code.toLowerCase();
    switch (code) {
      case 'econnaborted':
        message = '请求超时';
        break;
      default:
        message = '服务器接口异常';
        break;
    }

    notification({
      title: '提示',
      message,
      type: 'error'
    })
    return Promise.reject(error);
  }
)

export {
  http,
  CODE
};